package com.ningxun.rms.task;

import com.alibaba.fastjson2.JSONObject;
import com.ningxun.rms.domain.Access.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.concurrent.TimeUnit;
@Component("wechatAccessTokenTask")
public class WechatAccessTokenTask {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisTemplate redisTemplate;


    @Value("${wechat.appId:''}")
    private String appid;
    @Value("${wechat.secret:''}")
    private String secret;

    private static final String TOKEN_KEY = "WECHAT_JS_SDKTOKEN";
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WechatAccessTokenTask.class);
    public void refreshToken(){
        String url = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/stable_token")
                .toUriString();

        AccessToken accessToken = new AccessToken("client_credential" , appid ,secret);

        JSONObject res = restTemplate.postForObject(url, accessToken , JSONObject.class);

        String sdk = this.getTicket(res.get("access_token").toString());

        if(sdk != null){
            logger.info("sdk为" + res.containsKey("access_token"));
            // 存入redis
            //sdk的有效时间和accesstoken时间一样，这里直接用了
            redisTemplate.opsForValue().set(TOKEN_KEY, sdk,
                    res.getIntValue("expires_in"), TimeUnit.SECONDS);
        }else {
            logger.info("sdk获取失败.");
        }

        // 当token获取后
//        if (res.containsKey("access_token")) {
//            logger.info("access_token为" + res.containsKey("access_token"));
//            // 存入redis
//            redisTemplate.opsForValue().set(TOKEN_KEY, res.get("access_token"),
//                    res.getIntValue("expires_in"), TimeUnit.SECONDS);
//        } else {
//            //  记录日志
//            logger.info("access_token获取失败.");
//        }
    }

    private String getTicket(String access_token){
//        GET https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=TYPE
        String url = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/ticket/getticket" )
                .queryParam("access_token" , access_token)
                .queryParam("type" ,"wx_card")
                .toUriString();
        JSONObject res = restTemplate.getForObject(url, JSONObject.class);
        return res.get("ticket").toString();
    }

}


